#!/usr/bin/env python3
# -*- coding:utf-8 -*-

# requirement: linux python:3.8
# sudo apt install python3-pip
# pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple openpyxl==2.5

#导入内置包
import glob,datetime,os,base64
from xml.dom import minidom
import tkinter as tk
from tkinter import messagebox
import configparser
import shutil
from datetime import date

# 导入需要安装的包
from openpyxl import Workbook, load_workbook
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Inches, Pt

#任免表类
class Lrmx:
    '''
    解析任免表
    '''
    def __init__(self, filename):
        self.filename = filename
        self.dom = minidom.parse(self.filename)

    def Update(self, BiaoQian2, Zhi):
        item = self.dom.getElementsByTagName(BiaoQian2)[0]


        if item.firstChild is not None:
            item.firstChild.data = Zhi
        else:
            print(f"{BiaoQian2}is None")

        return True

    def GetValue(self, BiaoQian2):
#        print(BiaoQian)
        try:
            item = self.dom.getElementsByTagName(BiaoQian2)[0]
            return item.firstChild.data
        except Exception as e:
            print("出现异常：",e)
            return ""

##################UI
#BiaoQian, inpath, outpath,config = None
def main():
    global BiaoQian, inpath, outpath,config
    ##加载配置
    config = configparser.ConfigParser()
    config.read('./2-模板/config.ini')
    # 获取默认配置项
    inpath = config.get('DEFAULT', 'inpath')
    outpath = config.get('DEFAULT', 'outpath')
    BiaoQian = config.get('DEFAULT', 'BiaoQian').split(",")
    # 创建文件夹
    if not os.path.exists(inpath):
        os.mkdir(inpath)
    if not os.path.exists(outpath):
        os.mkdir(outpath)

    global root,window_width,window_height
    root = tk.Tk()
    root.title("任免表编辑工具")

    # 设置窗口的背景颜色为银灰色，可以使用颜色名称或十六进制颜色代码
    #root.config(bg='silver')  # 使用颜色名称
    # 或者
    root.config(bg='#333333')  # 使用十六进制颜色代码
    #root.configure(bg='purple') #紫色
    # 设置窗口大小和位置
    window_width = 1000
    window_height = 500
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width / 2) - (window_width / 2)
    y = (screen_height / 2) - (window_height / 2)
    root.geometry('%dx%d+%d+%d' % (window_width, window_height, x, y))

    # 设置主窗口按钮
    生成表格 = tk.Button(root, text="生成汇总表", width=30, height=2,command=on_generate_table_click, bg="lightblue")
    生成表格.grid(row=0, column=0, padx=10, pady=10)

    生成档案审核表 = tk.Button(root, text="生成档案审核表", bg="lightblue", command=ShengChengDASHB, width=30, height=2)
    生成档案审核表.grid(row=0, column=1, padx=10, pady=10)

    生成晋升审批表 = tk.Button(root, text="生成晋升审批表", bg="lightblue", command=ShengChengJSB, width=30, height=2)
    生成晋升审批表.grid(row=0, column=2, padx=10, pady=10)

    生成试用期满考核表 = tk.Button(root, text="生成试用期满考核表", bg="lightblue", command=ShengChengSYQ, width=30, height=2)
    生成试用期满考核表.grid(row=1, column=2, padx=10, pady=10)

    批量修改填表时间计算年龄时间 = tk.Button(root, text="批量修改填表时间\n计算年龄时间", bg="lightblue", width=30, height=2,command=ChangeTime)
    批量修改填表时间计算年龄时间.grid(row=1, column=0, padx=10, pady=10)

    批量修改填表人 = tk.Button(root, text="批量修改填表人", bg="lightblue", command=ChangeTianBiaoRen, width=30, height=2)
    批量修改填表人.grid(row=1, column=1, padx=10, pady=10)

    批量修改拟任拟免 = tk.Button(root, text="批量修改拟任拟免职务", bg="lightblue", command=ChangeNirenNimian, width=30, height=2)
    批量修改拟任拟免.grid(row=2, column=0, padx=10, pady=10)

    批量修改任免表文件名 = tk.Button(root, text="批量修改任免表文件名", bg="lightblue", command=ChangeWenjianming, width=30, height=2)
    批量修改任免表文件名.grid(row=2, column=1, padx=10, pady=10)

    生成退休文件 = tk.Button(root, text="生成退休文件", bg="lightblue", command=TuiXiu, width=30, height=2)
    生成退休文件.grid(row=2, column=2, padx=10, pady=10)
    
    追加年度考核结果 = tk.Button(root, text="追加年度考核结果", width=30, height=2,command=ZhuiJiaKaoHe, bg="lightblue")
    追加年度考核结果.grid(row=3, column=0, padx=10, pady=10)

    更新简历 = tk.Button(root, text="更新简历", width=30, height=2,command=GengXinJL, bg="lightblue")
    更新简历.grid(row=3, column=1, padx=10, pady=10)

    生成职级晋升文件 = tk.Button(root, text="生成职级晋升文件", width=30, height=2,command=JinShengFaWen, bg="lightblue")
    生成职级晋升文件.grid(row=4, column=0, padx=10, pady=10)

    使用说明 = tk.Button(root, text="使用说明", bg="lightblue",width=20, height=2, command=readme)
    使用说明.grid(row=5, column=0, padx=10, pady=10)

    打开输出文件夹 = tk.Button(root, text="打开输出文件夹", bg="lightblue",width=20, height=2, command=startFile)
    打开输出文件夹.grid(row=5, column=1, padx=10, pady=10)


    移动文件 = tk.Button(root, text="输入文件移动到\n源任免表文件夹", bg="lightblue",width=20, height=2, command=YiDongWenJian)
    移动文件.grid(row=4, column=1, padx=10, pady=10)


    root.mainloop()

def set_cell_font_size(cell, font_size):  
    """  
    设置表格单元格中所有文本的字体大小  
    :param cell: 要设置的单元格对象  
    :param font_size: 字体大小，例如 Pt(14)  
    """  
    for paragraph in cell.paragraphs:  
        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        for run in paragraph.runs:  
            run.font.size = font_size
            run.font.name = 'Times New Roman'
            

#生成退休文件
def TuiXiu():
    j = 0
    for filename in glob.glob(inpath+'*.lrmx'):
        global PersonDx
        PersonDx = Lrmx(filename)

        Docdb = "./2-模板/退休发文模板.docx"
        doc=Document(Docdb)
        tb=doc.tables
     
        XM = PersonDx.GetValue("XingMing")
        XingBie =  PersonDx.GetValue("XingBie")
        ChuSheng = PersonDx.GetValue("ChuShengNianYue")
        CanJiaGongZuoShiJian = PersonDx.GetValue("CanJiaGongZuoShiJian")
        TuiXiuSJ = str(int(ChuSheng[0:4]) + 60) + "." + str(ChuSheng[4:6])   if  XingBie == "男"  else   str(int(ChuSheng[0:4]) + 55) + "." + str(ChuSheng[4:6])
        ZhiXing =  str(int(TuiXiuSJ[0:4]) + 1) + "年1月"  if  TuiXiuSJ[:-2] == "12" else  TuiXiuSJ[:4] + "年" + str(int(TuiXiuSJ[5:7]) +1) + "月"
        


        # 替换字段
        DICT = {"替名":XM, "执行时间":ZhiXing}
        def replace_obj(doc_obj):
            for key, value in DICT.items():
                if key in doc_obj.text:
                    print(f"正在修改{key}为{value}")
                    doc_obj.text = doc_obj.text.replace(key, value)

        for para in doc.paragraphs:
            #替换块，不清除格式，但不同块不能替换
            for i in range(len(para.runs)):
                replace_obj(para.runs[i])


        #  基本信息
        JuZhong(tb[0].cell(0,1),"XingMing")
        set_cell_font_size(tb[0].cell(0,1),Pt(14))
        JuZhong(tb[0].cell(0,3),"XingBie")
        set_cell_font_size(tb[0].cell(0,3),Pt(14))
        JuZhong(tb[0].cell(0,5),"ChuShengNianYue")
        set_cell_font_size(tb[0].cell(0,5),Pt(14))
        JuZhong(tb[0].cell(1,1),"CanJiaGongZuoShiJian")
        set_cell_font_size(tb[0].cell(1,1),Pt(14))
        JuZhong(tb[0].cell(1,4),"ShenFenZheng")
        set_cell_font_size(tb[0].cell(1,4),Pt(14))
        tb[0].cell(2,4).text = TuiXiuSJ
        set_cell_font_size(tb[0].cell(2,4),Pt(14))
        # 计发比例，工作年限满35年的，按90%计发，满30年不满35年的按85%计发，其它的空白，手写
        CanGong = date(int(CanJiaGongZuoShiJian[0:4]),int(CanJiaGongZuoShiJian[4:6]),1)
        TuiXiu = date(int(TuiXiuSJ[0:4]),int(TuiXiuSJ[5:7]),1)
        # 计算两个日期之间的间隔年份数
        interval_years = TuiXiu - CanGong 
        years = interval_years.days / 365.25
        if years >= 35:
            tb[0].cell(3,4).text = "90%"
        elif years >= 30 and years <35:
            tb[0].cell(3,4).text = "85%"
        set_cell_font_size(tb[0].cell(3,4),Pt(14))
        
        doc.save('{0}/退休发文-{1}.docx'.format(outpath,XM))

        j += 1
    messagebox.showinfo("提示", f"生成{j}人")

   
# 打开输出文件夹
def startFile():
    os.startfile(outpath)

##1-生成表格回调函数
#1-根据任免表，生成上会表格
def ShengChengBiaoGe():
    #表格创建
    book = Workbook()
    sheet = book["Sheet"]

    #添加标题行
    sheet.append(BiaoQian)

    #遍历lrmx文件
    global j
    j=0
    for filename in glob.glob(f"{inpath}*.lrmx"):
        PersonDx=Lrmx(filename)
        Persion = []
        print(filename)
        for i in BiaoQian:
            va =  PersonDx.GetValue(i)
            if i in ["ChuShengNianYue","CanJiaGongZuoShiJian","RuDangShiJian"]:
                va = va[:4] + "." + va[-2:]
            if i == "ZaiZhiJiaoYu_XueLi" and va == '\n  ':
                va = PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi")

            Persion.append(va)
        sheet.append(Persion)
        j = j + 1
#        print("生成{}人".format(j))

    #保存文件
    today = datetime.date.today()
    book.save(outpath+str(today)+"生成表格.xlsx")

def on_generate_table_click():
    ShengChengBiaoGe()
    messagebox.showinfo("提示", f"生成{j}人")


##生成晋升审批表
def ShengChengJSB():
    j = 0
    for filename in glob.glob(inpath+'*.lrmx'):
        global PersonDx
        PersonDx = Lrmx(filename)
        XM = PersonDx.GetValue("XingMing")
        Docdb = "./2-模板/事业单位管理岗位职员等级晋升审批表模板.docx"
        doc=Document(Docdb)
        tb=doc.tables
        #  基本信息
        JuZhong(tb[0].cell(0,1),"XingMing")
        JuZhong(tb[0].cell(0,4),"XingBie")
        JuZhong(tb[0].cell(0,6),"ChuShengNianYue")
        JuZhong(tb[0].cell(1,1),"JiGuan")
        JuZhong(tb[0].cell(1,4),"MinZu")
        #入党时间
        if PersonDx.GetValue("RuDangShiJian")[:2] in ['19','20']:
            tb[0].cell(1,6).text = "中共党员"
        tb[0].cell(2,2).text = PersonDx.GetValue("ShenFenZheng")
        #  学历学位
        tb[0].cell(3,3).text = (PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi") +"\n"+ PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei")).rstrip()
        tb[0].cell(3,6).text = (PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi_BiYeYuanXiaoXi") + "\n"+ PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei_BiYeYuanXiaoXi")).rstrip()

        tb[0].cell(4,3).text = (PersonDx.GetValue("ZaiZhiJiaoYu_XueLi") + "\n" + PersonDx.GetValue("ZaiZhiJiaoYu_XueWei")).rstrip()
        tb[0].cell(4,6).text = (PersonDx.GetValue("ZaiZhiJiaoYu_XueLi_BiYeYuanXiaoXi") +"\n" + PersonDx.GetValue("ZaiZhiJiaoYu_XueWei_BiYeYuanXiaoXi")).rstrip()
        #简历、现任、拟任职务
        JL = PersonDx.GetValue("JianLi")
        tb[0].cell(5,1).text = JL
        tb[0].cell(6,2).text = PersonDx.GetValue("XianRenZhiWu")
        tb[0].cell(7,6).text = PersonDx.GetValue("NiRenZhiWu")
        
        #任现岗位时间
        index = JL.find("--       ")
        XZSJ = JL[index - 7:index]
        tb[0].cell(7,2).text = XZSJ
        

        
        #  照片
        image_path = f'{outpath}/image{XM}.jpg'
        ZP_t = tb[0].cell(0,7)
        ZP = base64.b64decode(PersonDx.GetValue("ZhaoPian"))
        with open(image_path, 'wb') as f:
            f.write(ZP)
        paragraph = ZP_t.paragraphs[0]
        run = paragraph.add_run()
        run.add_picture(image_path, width=Inches(1.0))
        #paragraph_format = paragraph.paragraph_format
        #paragraph_format.line_spacing = WD_LINE_SPACING.SINGLE
        
        doc.save('{0}/职员等级晋升审批表{1}.docx'.format(outpath,XM))
        os.remove(image_path)
        j += 1
    messagebox.showinfo("提示", f"生成{j}人")

### 追加年度考核结果 回调函数
def ZhuiJiaKaoHe():
    new_window = tk.Toplevel(root)
    new_window.title("追加年度考核结果")
    new_window.geometry(f"300x100+{int(window_width/2)}+{int(window_height/2)}")
    
    filename = os.path.join(os.getcwd(),"2-模板/模板.xlsx")
    def click():
        os.startfile(filename)
        
    def XieRu():
        wb = load_workbook(filename)
        ws = wb["Sheet1"]
        NianDu = ws['N1'].value
        i = 0
        for filename2 in glob.glob(inpath+'*.lrmx'):
            persion = Lrmx(filename2)
            #比对身份证
            for x in ws:
                if persion.GetValue("ShenFenZheng") == x[12].value:
                    KaoHeJieGuo1 = persion.GetValue("NianDuKaoHeJieGuo")
                    #判断是否已写
                    if NianDu[:4] in KaoHeJieGuo1:
                        break
                    
                    #追加年度考核结果
                    
                    KaoHeJieGuo2 = x[13].value
                    KaoHeJieGuo3 = KaoHeJieGuo1 + "；" + NianDu + str(KaoHeJieGuo2)
                    persion.Update("NianDuKaoHeJieGuo",KaoHeJieGuo3)

                    file=os.path.basename(filename2)
                    with open(outpath+file,'wb') as f:
                        f.write(persion.dom.toxml(encoding='utf-8'))
                    i = i+1
                    break
        else:
            new_window.destroy()
            messagebox.showinfo("提示", f"已完成,成功{i}人")
                
    label = tk.Label(new_window, text="1.请打开excle模板，并输入姓名、身份证号、2023年度考核结果。\n2.保存并关闭excle后点击”执行写入“")
    label.pack()

    button1 = tk.Button(new_window, text="打开excle",bg="lightblue", command=click)
    button1.pack(side="left",padx=20)    

    button2 = tk.Button(new_window, text="执行写入",bg="lightblue", command=XieRu)
    button2.pack(side="left",padx=20)    
     


    
 
#2-修改时间回调函数
def ChangeTime():
    new_window = tk.Toplevel(root)
    new_window.title("修改时间")
    new_window.geometry(f"300x100+{int(window_width/2)}+{int(window_height/2)}")
    
    label = tk.Label(new_window, text="请输入时间，例如20230101，填表时间清空：")
    label.pack()

    entry = tk.Entry(new_window)
    entry.pack()

    def click():
        time_input = entry.get()
        j=0
        for filename in glob.glob(inpath+'*.lrmx'):
            Person=Lrmx(filename)
            Person.Update("JiSuanNianLingShiJian",time_input)
            Person.Update("TianBiaoShiJian"," ")
            file=os.path.basename(filename)
            with open(outpath+file,'wb') as f:
                f.write(Person.dom.toxml(encoding='utf-8'))
            j=j+1
        else:
            new_window.destroy()
            messagebox.showinfo("提示", f"已完成, 共{j}人")

    button = tk.Button(new_window, text="确定", command=click)
    button.pack()
    
#3-修改填表人回调函数
def ChangeTianBiaoRen():
    new_window = tk.Toplevel(root)
    new_window.title("修改填表人")
    new_window.geometry(f"300x100+{int(window_width/2)}+{int(window_height/2)}")
    
    label = tk.Label(new_window, text="请输入填表人")
    label.pack()

    entry = tk.Entry(new_window)
    entry.pack()

    def click():
        time_input = entry.get()
        j=0
        for filename in glob.glob(inpath+'*.lrmx'):
            Person=Lrmx(filename)
            Person.Update("TianBiaoRen",time_input)
            file=os.path.basename(filename)
            with open(outpath+file,'wb') as f:
                f.write(Person.dom.toxml(encoding='utf-8'))
            j=j+1
        else:
            new_window.destroy()
            messagebox.showinfo("提示", f"已完成, 共{j}人")

    button = tk.Button(new_window, text="确定", bg="lightblue", command=click)
    button.pack()
   
#4-修改拟任拟免回调函数
def ChangeNirenNimian():
    new_window = tk.Toplevel(root)
    new_window.title("修改拟任拟免职务")
    new_window.geometry(f"300x100+{int(window_width/2)}+{int(window_height/2)}")
    
    filename = os.path.join(os.getcwd(),"2-模板/模板.xlsx")
    def click():
        os.startfile(filename)
        
    def XieRu():
        wb = load_workbook(filename)
        ws = wb["Sheet1"]
        i = 0
        for filename2 in glob.glob(inpath+'*.lrmx'):
            persion = Lrmx(filename2)
            #比对姓名
            for x in ws:
                if persion.GetValue("XingMing") == x[1].value:
                #修改拟任拟免
                    persion.Update("NiRenZhiWu",  "" if x[8].value is None else x[8].value)
                    persion.Update("NiMianZhiWu", "" if x[9].value is None else x[9].value)
                    file=os.path.basename(filename2)
                    with open(outpath+file,'wb') as f:
                        f.write(persion.dom.toxml(encoding='utf-8'))
                    i = i+1
                    break
        else:
            new_window.destroy()
            messagebox.showinfo("提示", f"已完成,成功{i}人")
                
    label = tk.Label(new_window, text="1.请打开excle模板，并输入姓名、拟任职务、拟免职务。\n2.保存并关闭excle后点击”执行写入“")
    label.pack()

    button1 = tk.Button(new_window, text="打开excle",bg="lightblue", command=click)
    button1.pack(side="left",padx=20)

    button2 = tk.Button(new_window, text="执行写入",bg="lightblue", command=XieRu)
    button2.pack(side="left",padx=20)
   
#5-修改文件名
def ChangeWenjianming():
    new_window = tk.Toplevel(root)
    new_window.title("修改文件名")
    new_window.geometry(f"300x100+{int(window_width/2)}+{int(window_height/2)}")
    
    filename = os.path.join(os.getcwd(),"2-模板/模板.xlsx")
    def click():
        os.startfile(filename)
        
    def XieRu():
        wb = load_workbook(filename)
        ws = wb["Sheet1"]
        i = 0
        for filename2 in glob.glob(inpath+'*.lrmx'):
            persion = Lrmx(filename2)
            #比对姓名
            for x in ws:
                if persion.GetValue("XingMing") == x[1].value:
                
                #修改文件名
                    with open(outpath+f"{x[0].value:02}"+"-"+x[1].value+".lrmx",'wb') as f:
                        f.write(persion.dom.toxml(encoding='utf-8'))
                    i = i+1
                    break
        else:
            new_window.destroy()
            messagebox.showinfo("提示", f"已完成,成功{i}人")
                
    label = tk.Label(new_window, text="1.请打开excle模板，并输入序号、姓名。\n2.保存并关闭excle后点击”执行修改“")
    label.pack()

    button1 = tk.Button(new_window, text="打开excle",bg="lightblue", command=click)
    button1.pack(side="left",padx=20)    

    button2 = tk.Button(new_window, text="执行修改",bg="lightblue", command=XieRu)
    button2.pack(side="left",padx=20)
 
#-使用说明
def readme():
    os.startfile(os.path.join(os.getcwd(), "2-模板/readme.txt"))


def JuZhong(cell,y):
    # 获取单元格中的段落
    paragraph = cell.paragraphs[0]
    # 设置段落文本居中对齐
    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    # 设置段落文本内容
    if y in ['RuDangShiJian','CanJiaGongZuoShiJian','ChuShengNianYue']:
        x = PersonDx.GetValue(y)[:4] + '.' + PersonDx.GetValue(y)[4:6]
        paragraph.add_run(x)
    else:
        paragraph.add_run(PersonDx.GetValue(y))
        
#  生成档案审核表
def ShengChengDASHB():
    j = 0
    for filename in glob.glob(inpath+'*.lrmx'):

        global PersonDx
        PersonDx = Lrmx(filename)
        Docdb = "./2-模板/干部档案审核情况表模板.docx"
        doc=Document(Docdb)
        tb=doc.tables
        #三龄填写
        JuZhong(tb[0].cell(0,2),"XingMing")
        tb[0].cell(0,4).text = PersonDx.GetValue("XianRenZhiWu")
        JuZhong(tb[0].cell(1,2),"ChuShengNianYue")
        JuZhong(tb[0].cell(1,4),"CanJiaGongZuoShiJian")
        JuZhong(tb[0].cell(1,6),"RuDangShiJian")
        #学历学位填写
        tb[0].cell(2,3).text = PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi")
        tb[0].cell(2,5).text = PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi_BiYeYuanXiaoXi")
        tb[0].cell(3,3).text = PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei")
        tb[0].cell(3,5).text = PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei_BiYeYuanXiaoXi")
        tb[0].cell(4,3).text = PersonDx.GetValue("ZaiZhiJiaoYu_XueLi")
        tb[0].cell(4,5).text = PersonDx.GetValue("ZaiZhiJiaoYu_XueLi_BiYeYuanXiaoXi")
        tb[0].cell(5,3).text = PersonDx.GetValue("ZaiZhiJiaoYu_XueWei")
        tb[0].cell(5,5).text = PersonDx.GetValue("ZaiZhiJiaoYu_XueWei_BiYeYuanXiaoXi")
        #保存
        doc.save('{0}/干部档案任免审核表{1}.docx'.format(outpath,PersonDx.GetValue("XingMing")))
        j += 1
    messagebox.showinfo("提示", f"生成{j}人")

## 更新简历
def GengXinJL():
    new_window = tk.Toplevel(root)
    new_window.title("更新简历")
    new_window.geometry(f"300x150+{int(window_width/2)}+{int(window_height/2)}")
    def click():
        os.startfile(filename)

    def XieRu():
        wb = load_workbook(filename)
        ws = wb["Sheet1"]
        i = 0
        for filename2 in glob.glob(inpath+'*.lrmx'):
            persion = Lrmx(filename2)
            #比对姓名
            for x in ws:
                if persion.GetValue("XingMing") == x[1].value:
                    #获取数据：新职务、任职时间
                    RenZhiSJ = entry.get()
                    XinZhiWu = x[10].value

                    #修改简历
                    JianLi = persion.GetValue("JianLi").replace("--       ","--" + RenZhiSJ)
                    JianLi = JianLi + '\n' + RenZhiSJ + "--         " +  XinZhiWu
                    persion.Update("JianLi",  JianLi)

                    #修改现任职务、拟任职务（空）、拟免职务（空）
                    persion.Update("XianRenZhiWu", XinZhiWu)
                    try:
                        persion.Update("NiRenZhiWu", "")
                    finally:pass
                    try:
                        persion.Update("NiMianZhiWu", "")
                    finally:pass
                    #保存
                    file=os.path.basename(filename2)
                    with open(outpath+file,'wb') as f:
                        f.write(persion.dom.toxml(encoding='utf-8'))
                    i = i+1
                    break
        else:
            new_window.destroy()
            messagebox.showinfo("提示", f"已完成,成功{i}人")


    label = tk.Label(new_window, text="1.请打开excle模板，并输入姓名、新职务。\n2.保存并关闭excle。 \n 3.输入任职时间，如2024.06，点击”更新简历“",anchor="w")
    label.pack()

    entry = tk.Entry(new_window)
    entry.pack()

    button1 = tk.Button(new_window, text="打开excle",bg="lightblue", command=click)
    button1.pack(side="left",padx=20)

    button2 = tk.Button(new_window, text="更新简历",bg="lightblue", command=XieRu)
    button2.pack(side="left",padx=20)
    filename = os.path.join(os.getcwd(),"2-模板/模板.xlsx")

### 移动文件
def YiDongWenJian():
    new_window = tk.Toplevel(root)
    new_window.title("移动文件")
    new_window.geometry(f"300x150+{int(window_width/2)}+{int(window_height/2)}")

    label = tk.Label(new_window, text="此操作会删除源任免表文件夹所有内容，请谨慎操作",anchor="w")
    label.pack()

    def YiDongWJ():
        i =0
        j =0
        def delete_files_in_folder(folder_path):
            nonlocal i
            for filename in os.listdir(folder_path):
                file_path = os.path.join(folder_path, filename)
                if os.path.isfile(file_path):
                    os.remove(file_path)
                i = i + 1

        # 将文件夹"3-输出文件"中的所有内容剪切到文件夹"1-源任免表"中
        def move_folder_contents(src_folder, dst_folder):
            nonlocal j
            for item in os.listdir(src_folder):
                item_path = os.path.join(src_folder, item)
                dst_item_path = os.path.join(dst_folder, item)
                shutil.move(item_path, dst_item_path)
                j = j + 1

        delete_files_in_folder(inpath)
        move_folder_contents(outpath,inpath)

        new_window.destroy()
        messagebox.showinfo("提示", f"已完成,删除{i}个文件，移动{j}个文件")

    button2 = tk.Button(new_window, text="确定",bg="lightblue", command=YiDongWJ)
    button2.pack(side="right",padx=20)

##晋升发文函数
def JinShengFaWen():
    new_window = tk.Toplevel(root)
    new_window.title("晋升发文")
    new_window.geometry(f"300x150+{int(window_width/2)}+{int(window_height/2)}")
    
    def click():
        os.startfile(filename)
        
    def XieRu():
        wb = load_workbook(filename)
        ws = wb["Sheet1"]
        
        text2 = ""
        DanWei_old = None
        #比对姓名
        for x in ws:
            XingMing2 = x[1].value
            NiRen = x[8].value
            DanWei_new = x[14].value

            text = XingMing2 + "同志晋升为" + DanWei_new +NiRen + "；\n"
            text_1 = "同志晋升为" + DanWei_new +NiRen + "；\n"

            text2 = text2 + text
            if DanWei_new ==  DanWei_old:
                text2 = text2.replace(text_1,"、",1)
            else:
                pass
        
            DanWei_old  = DanWei_new
        text2 = text2.replace("县直机关","").replace("乡镇机关","")
        file = open(outpath+"职级晋升发文拟稿.txt", 'w')
        file.write(text2)
        file.close()
        
        new_window.destroy()
        messagebox.showinfo("提示", "生成成功！！！，请到输出文件夹中查看")
        os.startfile(outpath)


    label = tk.Label(new_window, text="1.请打开excle模板，并输入姓名、新职务、单位。\n2.保存并关闭excle。",anchor="w")
    label.pack()

    button1 = tk.Button(new_window, text="打开excle",bg="lightblue", command=click)
    button1.pack(side="left",padx=20)

    button2 = tk.Button(new_window, text="生成发文",bg="lightblue", command=XieRu)
    button2.pack(side="left",padx=20)
    filename = os.path.join(os.getcwd(),"2-模板/模板.xlsx")

##生成试用满考核表
def ShengChengSYQ():
    j = 0
    for filename in glob.glob(inpath+'*.lrmx'):
        global PersonDx
        PersonDx = Lrmx(filename)
        XM = PersonDx.GetValue("XingMing")
        #生成试用期考核表
        Docdb = "./2-模板/附件1-试用期满考核表.docx"
        doc=Document(Docdb)
        tb=doc.tables
        #  基本信息
        JuZhong(tb[0].cell(0,1),"XingMing")
        JuZhong(tb[0].cell(0,3),"XingBie")
        JuZhong(tb[0].cell(0,5),"ChuShengNianYue")
        #JuZhong(tb[0].cell(1,1),"JiGuan")
        #JuZhong(tb[0].cell(1,4),"MinZu")
        #政治面貌
        if PersonDx.GetValue("RuDangShiJian")[:2] in ['19','20']:
            tb[0].cell(1,1).text = "中共党员"
        else:
            tb[0].cell(1,1).text = PersonDx.GetValue("RuDangShiJian")
        #tb[0].cell(2,2).text = PersonDx.GetValue("ShenFenZheng")
        #  学历学位
        if len(PersonDx.GetValue("ZaiZhiJiaoYu_XueLi")) > 1:
            tb[0].cell(1,3).text = (PersonDx.GetValue("ZaiZhiJiaoYu_XueLi") + "\n" + (PersonDx.GetValue("ZaiZhiJiaoYu_XueWei"))).rstrip()
        else:
            tb[0].cell(1,3).text = (PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi") + "\n" + (PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei"))).rstrip()
        # 简历、现任、拟任职务
        tb[0].cell(2,1).text = PersonDx.GetValue("XianRenZhiWu")
        #保存
        doc.save('{0}/试用期满考核表-{1}.docx'.format(outpath,XM))

        # 生成任职定级审批表
        Docdb2 = "./2-模板/附件2-任职定级审批表.docx"
        doc2=Document(Docdb2)
        tb=doc2.tables
        #  基本信息
        JuZhong(tb[0].cell(0,2),"XingMing")
        JuZhong(tb[0].cell(0,5),"XingBie")
        JuZhong(tb[0].cell(0,7),"ChuShengNianYue")
        JuZhong(tb[0].cell(1,2),"JiGuan")
        JuZhong(tb[0].cell(0,9),"MinZu")
        JuZhong(tb[0].cell(1,8),"JianKangZhuangKuang")
        JuZhong(tb[0].cell(2,3),"CanJiaGongZuoShiJian")
        #政治面貌
        if PersonDx.GetValue("RuDangShiJian")[:2] in ['19','20']:
            tb[0].cell(1,6).text = "中共党员"
        else:
            JuZhong(tb[0].cell(1,6),"RuDangShiJian")
        #  学历学位
        #全日制教育，如果有学位一样只输出一个
        tb[0].cell(3,4).text = (PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi") + "\n" + PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei")).rstrip()
        if PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi_BiYeYuanXiaoXi") == PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei_BiYeYuanXiaoXi"):
            tb[0].cell(3,8).text = PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi_BiYeYuanXiaoXi").rstrip()
        else:
            tb[0].cell(3,8).text = (PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi_BiYeYuanXiaoXi") + "\n" + PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei_BiYeYuanXiaoXi")).rstrip()
        #在职教育
        tb[0].cell(4,4).text = (PersonDx.GetValue("ZaiZhiJiaoYu_XueLi") + "\n" +  PersonDx.GetValue("ZaiZhiJiaoYu_XueWei")).rstrip()
        tb[0].cell(4,8).text = (PersonDx.GetValue("ZaiZhiJiaoYu_XueLi_BiYeYuanXiaoXi") + "\n" + PersonDx.GetValue("ZaiZhiJiaoYu_XueWei_BiYeYuanXiaoXi")).rstrip()

        # 简历、现任、拟任职务
        tb[0].cell(5,2).text = PersonDx.GetValue("XianRenZhiWu")
        tb[0].cell(7,2).text = PersonDx.GetValue("JianLi")
        #保存
        doc2.save('{0}/任职定级审批表-{1}.docx'.format(outpath,XM))


        # 生成公务员登记表
        Docdb = "./2-模板/附件3-公务员登记表.docx"
        doc=Document(Docdb)
        tb=doc.tables
        #  基本信息
        JuZhong(tb[0].cell(0,2),"XingMing")
        JuZhong(tb[0].cell(0,6),"XingBie")
        JuZhong(tb[0].cell(0,9),"ChuShengNianYue")
        JuZhong(tb[0].cell(1,2),"JiGuan")
        JuZhong(tb[0].cell(1,5),"MinZu")
        JuZhong(tb[0].cell(2,9),"JianKangZhuangKuang")
        JuZhong(tb[0].cell(2,5),"CanJiaGongZuoShiJian")
        JuZhong(tb[0].cell(3,2),"ShenFenZheng")
        
        #政治面貌
        if PersonDx.GetValue("RuDangShiJian")[:2] in ['19','20']:
            tb[0].cell(1,9).text = "中共党员"
            JuZhong(tb[0].cell(2,3),"RuDangShiJian")
        else:
            tb[0].cell(1,9).text = PersonDx.GetValue("RuDangShiJian")
        #  学历学位
        tb[0].cell(4,3).text = (PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi") + '\n'  + PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei")).rstrip()
        #如果毕业院校一样，只显示一次
        if PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi_BiYeYuanXiaoXi") == PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei_BiYeYuanXiaoXi"):
            tb[0].cell(4,8).text = (PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi_BiYeYuanXiaoXi")).rstrip()
        else:
            tb[0].cell(4,8).text = (PersonDx.GetValue("QuanRiZhiJiaoYu_XueLi_BiYeYuanXiaoXi") + '\n' + PersonDx.GetValue("QuanRiZhiJiaoYu_XueWei_BiYeYuanXiaoXi")).rstrip()

        tb[0].cell(5,4).text = (PersonDx.GetValue("ZaiZhiJiaoYu_XueLi") + PersonDx.GetValue("ZaiZhiJiaoYu_XueWei")).rstrip()
        tb[0].cell(5,8).text = (PersonDx.GetValue("ZaiZhiJiaoYu_XueLi_BiYeYuanXiaoXi") + PersonDx.GetValue("ZaiZhiJiaoYu_XueWei_BiYeYuanXiaoXi")).rstrip()

        # 简历、现任、拟任职务
        tb[0].cell(7,2).text = PersonDx.GetValue("JianLi")
        tb[0].cell(6,3).text = PersonDx.GetValue("XianRenZhiWu")

        #  照片
        image_path = f'{outpath}/image{XM}.jpg'
        ZP_t = tb[0].cell(0,10)
        ZP = base64.b64decode(PersonDx.GetValue("ZhaoPian"))
        with open(image_path, 'wb') as f:
            f.write(ZP)
        paragraph = ZP_t.paragraphs[0]
        run = paragraph.add_run()
        run.add_picture(image_path, width=Inches(1.0))
        
        #保存
        doc.save('{0}/公务员登记表-{1}.docx'.format(outpath,XM))
        os.remove(image_path)
        j += 1
    messagebox.showinfo("提示", f"生成{j}人")



if __name__ == '__main__':
    main()
